package com.campusflea.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.campusflea.DateBase.ShopInfo;
import com.campusflea.DateBase.UserInfo;
import com.campusflea.GoodsDetailsActivity;
import com.campusflea.LoginActivity;
import com.campusflea.MainActivity;
import com.campusflea.R;
import com.campusflea.ReleaseActivity;
import com.campusflea.adapter.MyAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.SQLQueryListener;

/**
 * Created by Administrator on 2017/5/31 0031.
 */

public class FragmentMain extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
    private ArrayList<HashMap<String, Object>> listArray;
    private HashMap<String, Object> map1;
    private ListView lv;
    private RelativeLayout invis;
    private Button btn1,btn2,btn3,btn4,btn11,btn22,btn33,btn44;
    private ImageButton btn_class1,btn_class2,btn_class3,btn_class4,
                        btn_class5,btn_class6,btn_class7,btn_class8;
    private List<ShopInfo> list;
    private Bitmap[] bitmapsImage;
    private  SwipeRefreshLayout swipeRefreshLayout;

    private String phone;
    private static final int REFRESH_COMPLETE = 0X110;

    public FragmentMain(String phone){
        this.phone=phone;
    }
    public FragmentMain(){

    }
    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case REFRESH_COMPLETE:
//                    mDatas.addAll(Arrays.asList("Lucene", "Canvas", "Bitmap"));
//                    mAdapter.notifyDataSetChanged();
                    swipeRefreshLayout.setRefreshing(false);
                    break;
            }
        };
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        View rootView = inflater.inflate(R.layout.activity_main_fram, null);
        lv = (ListView)rootView.findViewById(R.id.lv);
        invis = (RelativeLayout)rootView. findViewById(R.id.invis);
        swipeRefreshLayout= (SwipeRefreshLayout) rootView.findViewById(R.id.id_swipe_ly);
        swipeRefreshLayout.setOnRefreshListener(this);

        Bmob.initialize(getActivity(), "36b62198745ed1900e5f1e8d55eb660d");
        initDatas("");//获取数据
        initAdapter();//适配器添加
        btn1=(Button)rootView.findViewById(R.id.btn_all);
        btn2=(Button)rootView.findViewById(R.id.btn_sell);
        btn3=(Button)rootView.findViewById(R.id.btn_pai);
        btn4=(Button)rootView.findViewById(R.id.btn_change);
        btn11=(Button)rootView.findViewById(R.id.btn_all);
        btn22=(Button)rootView.findViewById(R.id.btn_sell);
        btn33=(Button)rootView.findViewById(R.id.btn_pai);
        btn44=(Button)rootView.findViewById(R.id.btn_change);
        btn_class1=(ImageButton)rootView.findViewById(R.id.class1);
        btn_class2=(ImageButton)rootView.findViewById(R.id.class2);
        btn_class3=(ImageButton)rootView.findViewById(R.id.class3);
        btn_class4=(ImageButton)rootView.findViewById(R.id.class4);
        btn_class5=(ImageButton)rootView.findViewById(R.id.class5);
        btn_class6=(ImageButton)rootView.findViewById(R.id.class6);
        btn_class7=(ImageButton)rootView.findViewById(R.id.class7);
        btn_class8=(ImageButton)rootView.findViewById(R.id.class8);

        btn1.setOnClickListener(lisenter);
        btn2.setOnClickListener(lisenter);
        btn3.setOnClickListener(lisenter);
        btn4.setOnClickListener(lisenter);
        btn11.setOnClickListener(lisenter);
        btn22.setOnClickListener(lisenter);
        btn33.setOnClickListener(lisenter);
        btn44.setOnClickListener(lisenter);
        btn_class1.setOnClickListener(lisenter1);
        btn_class2.setOnClickListener(lisenter1);
        btn_class3.setOnClickListener(lisenter1);
        btn_class4.setOnClickListener(lisenter1);
        btn_class5.setOnClickListener(lisenter1);
        btn_class6.setOnClickListener(lisenter1);
        btn_class7.setOnClickListener(lisenter1);
        btn_class8.setOnClickListener(lisenter1);
        //Toast.makeText(getActivity(),listShop.size() , Toast.LENGTH_SHORT).show();
        return rootView;
    }

    private void initAdapter() {
        lv.addHeaderView(View.inflate(getActivity(), R.layout.header, null));
        lv.addHeaderView(View.inflate(getActivity(), R.layout.header2, null));
        MyAdapter listAdapter = new MyAdapter(getActivity(), listArray);
        lv.setAdapter(listAdapter);

        lv.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem >= 2) {
                    invis.setVisibility(View.VISIBLE);
                } else {

                    invis.setVisibility(View.GONE);
                }
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                ShopInfo shopInfo = new ShopInfo();
                shopInfo=list.get(position -2);
                Intent intent =new Intent(getActivity(), GoodsDetailsActivity.class);
                Bundle mBundle = new Bundle();
                mBundle.putSerializable("shop",shopInfo);
                intent.putExtras(mBundle);
                intent.putExtra("phone",phone);
                startActivity(intent);
                Toast.makeText(getActivity(), "第" + (position -1) + "个"+"id="+list.get(position -2).getObjectId(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }
    
    private void initDatas(String type) {
        listArray = new ArrayList<HashMap<String, Object>>();
        BmobQuery<ShopInfo> query=new BmobQuery<ShopInfo>();
        String bql ="select * from ShopInfo";
        if(type!=""){
            bql +=" where shop_type=?";
            query.setPreparedParams(new Object[]{type});
        }
        query.setSQL(bql);
        query.doSQLQuery(new SQLQueryListener<ShopInfo>(){
            @Override
            public void done(BmobQueryResult<ShopInfo> bmobQueryResult, BmobException e) {
                list = (List<ShopInfo>) bmobQueryResult.getResults();
                if(list.size()==0){
                    Toast.makeText(getActivity(),"获取信息失败",Toast.LENGTH_LONG).show();
                }
                else {
                    Toast.makeText(getActivity(),"信息加载中。。。。",Toast.LENGTH_LONG).show();

                    for(int i=0;i<list.size();i++){
                        map1 = new HashMap<String, Object>();
                        downloadImage(list.get(i),map1);
                        map1.put("shop_name",list.get(i).getShop_name());
                        map1.put("shop_disc",list.get(i).getShop_disc());
                        map1.put("user_price",list.get(i).getShop_price());
                        listArray.add(map1);
                    }
                }
            }
        });
    }
    private void load(){
        MyAdapter listAdapter = new MyAdapter(getActivity(), listArray);
        lv.setAdapter(listAdapter);
    }


    //下载图片
    private void downloadImage(ShopInfo shopInfo, final HashMap<String, Object> map1) {
        BmobFile icon=shopInfo.getBmobFile();
        icon.download(new DownloadFileListener() {

            @Override
            public void onProgress(Integer integer, long l) {

            }

            @Override
            public void done(String s, BmobException e) {
               // imageView.setImageBitmap(BitmapFactory.decodeFile(s));   //根据地址解码并显示图片
               map1.put("shop_pic",BitmapFactory.decodeFile(s));
                //Log.e("eee111","e--->"+BitmapFactory.decodeFile(s));
            }
        });
    }

private View.OnClickListener lisenter = new View.OnClickListener() {
    public void onClick(View v) {
        Button btn =(Button)v;
        try{
            switch(btn.getId())
            {
                case R.id.button1: case R.id.btn_all: //四种分类（全部，买卖，拍卖，以物换物）
                initDatas("");load();
                break;
                case R.id.button2: case R.id.btn_sell:
                break;
                case R.id.button3: case R.id.btn_pai:
                break;
                case R.id.button4: case R.id.btn_change:
                break;
            }
        }catch(Exception e){}
    }
};
    private View.OnClickListener lisenter1 = new View.OnClickListener() {
        public void onClick(View v) {
            ImageButton btn =(ImageButton)v;
            try{
                switch(btn.getId())
                {
                    //八种分类
                    case R.id.class1:
                        //校园代步：  ---类型1
                        initDatas("校园代步");load();
                        break;
                    case R.id.class2:
                        //手机电脑
                        initDatas("手机电脑");load();
                        break;
                    case R.id.class3:
                        //电子配件
                        initDatas("电子配件");load();
                        break;
                    case R.id.class4:
                        //运动健身
                        initDatas("运动健身");load();
                        break;
                    case R.id.class5:
                        //图书教材
                        initDatas("图书教材");load();
                        break;
                    case R.id.class6:
                        //衣物伞帽
                        initDatas("衣物伞帽");load();
                        break;
                    case R.id.class7:
                        //生活娱乐
                        initDatas("生活娱乐");load();
                        break;
                    case R.id.class8:
                        //其他
                        initDatas("其他");load();
                        break;
                }
            }catch(Exception e){}
        }
    };

    @Override
    public void onRefresh() {
        mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 2000);
        initDatas("");load();
    }



}

